<?php

namespace App\Models\Developer;
use App\Http\Common\MyUtils;
use App\Models\BaseHardNew;
use App\Models\BaseOld;
use Illuminate\Support\Str;

/**
 * 开发者 套件
 * Class Developer
 * @package App\Models
 */
class DeveloperPackage extends BaseOld
{
    protected $table = "developer_packages";

    public $column = "*,(select count(*) from bf_developer_package_apps a where a.package_id=sa.id ) app_count";

    public function myQuery($request)
    {
        parent::myQuery($request);
        $this->sqlSearch($request,'developer_id','=');// 开发者id
        $this->sqlSearch($request,'name','like');
    }

    public function store($request)
    {
        $res = parent::store($request);
        if ($res){
            MyUtils::setRequest($request,'id',$res);
            $this->setUnique($request,$res);
            $res = self::storeUpdate($request);
        }
        return $res;
    }

    /**
     * 生成 套件Id  套件密钥 用于生成 accessToken使用的
     * @param $request
     * @param $uniqueId 唯一的id
     */
    public function setUnique(& $request,$uniqueId){
        // 生成 套件Id  套件密钥 用于生成 accessToken使用的
        MyUtils::setRequest($request,'unique_id',Str::random(14));
        MyUtils::setRequest($request,'unique_key',md5(Str::random(30).$uniqueId));
    }
    /**
     * 拥有的所有的app应用
     */
    public function apps(){
        return $this->hasMany(DeveloperPackageApp::class,'package_id');
    }

    protected static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static::deleting(function($models) {
            $apps = $models->apps->all();
            foreach ($apps as $k=>$v){
                $v->delete();
            }
        });
        static::updating(function($model) {
            if ($model->enable==2){// 为禁用,就同时 apps 禁用
                $apps = $model->apps;
                foreach ($apps as $k=>$v){
                    $v->update(['enable'=>2]);
                }
            }
        });
    }
}
